<?php
/*
 * @Descripttion: 
 * @version: 1.0
 * @Author: Sam
 * @Date: 2022-04-07 20:24:44
 * @LastEditors: Sam
 * @LastEditTime: 2023-01-05 10:16:15
 */
declare (strict_types=1);

namespace app\admin\controller;
use app\admin\model\User as UserModel;
use app\common\BaseController;
use hg\apidoc\annotation as Apidoc;
use think\Request;
use app\common\support\PHPExcelService;

/**
 * @Apidoc\Title("用户管理")
 **/
class User extends BaseController
{
    /**
     * @Apidoc\Title("列表")
     * @Apidoc\Url("user/index")
     * @Apidoc\Method("GET")
     * @Apidoc\Tag("account")
     * @Apidoc\Returned("data", type="array", desc="业务数据",replaceGlobal="true",
     *   @Apidoc\Returned("start",type="int",desc="起始位置"),
     *   @Apidoc\Returned("limit",type="int",desc="查询数量"),
     *   @Apidoc\Returned("data",type="array",desc="返回数据"),
     *   @Apidoc\Returned("total",type="array",desc="数据总量")
     * )
     */
    public function index(Request $request)
    {
        $page  = (int)$request->param('page', 0);
        $limit  = (int)$request->param('limit', 10);
        $search = request()->param();
        $wheres = [];
        if(isset($search['search_word']) && $search['search_word'] !=''){
            $wheres[] = ['nickname|mobile','like',"%{$search['search_word']}%"];
        }
        $query  = UserModel::where($wheres);
        $total  = $query->count();
        $data   = $query->page($page, $limit)->order('id desc')->select();
        return $this->success('', [
            'start' => $page,
            'limit' => $limit,
            'data'  => $data,
            'total' => $total,
        ]);
    }
    
    
    /**
     * 导出excell
     * @return void
     * @author Sam
     *
     */
    public function user_export_excell(){
        $search = request()->param();
        $wheres = [];
        if(isset($search['searchword']) && $search['searchword'] !=''){
            $wheres[] = ['nickname|mobile','like',"%{$search['searchword']}%"];
        }
        $title = ['用户id', '昵称','openid'];
        set_time_limit(0); // 设置超时时间
        $filename = '会员信息' . date('Ymdhis') . '.csv';
        header("Content-type:application/vnd.ms-csv");
        header('content-disposition:attachment; filename="' . $filename . '"');
        ob_end_flush();
        // ob_implicit_flush(true);
        // 写入导出标题
        echo iconv('utf-8', 'gbk', implode(',', $title)) . PHP_EOL;
        $lastId = 0;
        while (true) {
            $list =  UserModel::where($wheres)->limit(100)->order('id asc')->where('id','>',$lastId)->select()->toArray();
            if (!empty($list)) {
                foreach ($list as $user) {
                    $item = []; // 初始化数组
                    // 用户信息
                    $item[] = $user['id']; // id
                    $item[] = $user['nickname']; // 手机号
                    $item[] = $user['openid']; // openid
                    // 写入内容
                    echo iconv('utf-8', 'gbk//IGNORE', implode(',', $item)) . PHP_EOL;
                    $lastId = $user['id']; // 最大id
                }

            } else {
                break;
            }
        }
        exit;  
    }

    /**
     * 导入
     * @return void
     * @author Sam
     * 
     */
    public function user_import_excell(){
        if(empty($_FILES['file'])) json_response(0, '请选择文件');
        $list = big_csv_to_array($_FILES['file']['tmp_name']);
        try{
            $num = 0;
            if(count($list)){
                foreach($list as $k=>$v){
                    $data = [
                        'create_time'=>time(),
                        'update_time'=>time(),
                    ];
                $res =  UserModel::create($data);
                if($res) $num++;
                }
            }
                return  $this->success('导入成功'.$num.'条数据');
            }catch(\Exception $e){
                return $this->error($e->getMessage());
            }
    // try{
        // $list = PHPExcelService::read_excell();
        // $num = 0;
        // if(count($list)){
        //     foreach($list as $k=>$v){
        //         $data = [
        //             'nickname'=>$v[1],
        //             'mobile'=>$v[2],
        //             'openid' => md5($v[2]),
        //             'create_time'=>time(),
        //             'update_time'=>time(),
        //         ];
        //        $res =  UserModel::create($data);
        //        if($res) $num++;
        //     }
        // }
        //     return  $this->success('导入成功'.$num.'条数据');
        // }catch(\Exception $e){
        //     return $this->error($e->getMessage());
        // }
    }
    

        /**
     * @Apidoc\Title ("详情")
     * @Apidoc\Url("user/user/:id")
     * @Apidoc\Method("GET")
     * @Apidoc\Tag("account")
     * @Apidoc\Param("id", type="string", require=true, desc="账号id")
     * @Apidoc\Returned("data", type="array", desc="业务数据",replaceGlobal="true",
     *   @Apidoc\Returned("data",type="string",desc="账号信息")
     * )
     */
    public function detail(int $id): \think\response\Json
    {
        try {
            $row  = UserModel::where('id', $id)->find();
        } catch (DataNotFoundException | ModelNotFoundException | DbException $e) {
            return $this->error($e->getMessage());
        }

        return $this->success('', $row);
    }


        /**
     * @Apidoc\Title("创建")
     * @Apidoc\Url("user")
     * @Apidoc\Method("POST")
     * @Apidoc\Tag("account")
     * @Apidoc\Param("nickname", type="string", require=false, desc="昵称")
     * @Apidoc\Param("mobile", type="string", require=false, desc="头像")
     * @Apidoc\Param("mobile", type="string", require=false, desc="手机号码")
     */
    public function create(Request $request): \think\response\Json
    {
        $data = $request->post();
        try {
            $this->validate($data, [
                'nickname' => 'require',
            ], [
                'nickname.require'  => '昵称必须'
            ]);
        } catch (ValidateException $e) {
            return $this->error($e->getError());
        }
        $result = UserModel::create([
            'nickname'  => $data['nickname'],
            'mobile' => $data['mobile'],
            'avatar' => $data['avatar'],
            'openid' => $data['openid']
        ]);
        if ($result->isEmpty()) {
            return $this->error('错误');
        }

        return $this->success('成功');
    }


            /**
     * @Apidoc\Title("创建")
     * @Apidoc\Url("user")
     * @Apidoc\Method("POST")
     * @Apidoc\Tag("account")
     * @Apidoc\Param("nickname", type="string", require=false, desc="昵称")
     * @Apidoc\Param("mobile", type="string", require=false, desc="头像")
     * @Apidoc\Param("mobile", type="string", require=false, desc="手机号码")
     */
public function edit(Request $request): \think\response\Json
    {
        $data = $request->post();
        try {
            $this->validate($data, [
                'nickname' => 'require',
                'id'       => 'require',
            ], [
                'nickname.require'  => '昵称必须',
                'id.require'  => '主键必须'
            ]);
        } catch (\Exception $e) {
            return $this->error($e->getError());
        }
        $result = UserModel::update([
            'nickname'  => $data['nickname'],
            'mobile' => $data['mobile'],
            'avatar' => $data['avatar'],
            'openid' => $data['openid']
        ],['id'=>$data['id']]);
        if ($result->isEmpty()) {
            return $this->error('错误');
        }

        return $this->success('成功');
    }
}
